import type {Router} from 'vue-router';
import NProgress from 'nprogress'; // progress bar

// eslint-disable-next-line import/no-cycle
import usePermission from '@/hooks/permission';
// eslint-disable-next-line import/no-cycle
import {useMenuStore} from '@/store';
import {WHITE_LIST, NOT_FOUND, DEFAULT_ROUTE_NAME, DEFAULT_ROUTE_FULL_PATH} from '../constants';
import { isLogin } from '@/utils/auth';

export default function setupPermissionGuard(router: Router) {
    router.beforeEach(async (to, from, next) => {
        const menuStore = useMenuStore();
        // 未加载菜单 并且 不在白名单内 则加载菜单
        if (
            !menuStore.menuFetched &&
            !WHITE_LIST.find((el) => el.name === to.name)
        ) {
            // 加载菜单
            await menuStore.loadMenus();
        }
        const permission = usePermission();
        const access = permission.accessRouter(to);
        // 刚进入页面时 重定向的 meta 是空的
        if (access && to.meta.locale === undefined && menuStore.menuFetched) {
            to.meta = to.matched[to.matched.length - 1].meta;
        }
        if (access) {
          //判断是否登录 登录直接跳转到默认页面
            if (to.path == '/login' && isLogin()) {
                 next(DEFAULT_ROUTE_FULL_PATH);
            } else {
                // 正常跳转
                next();
            }
        } else {
            // 页面不存在
            next(NOT_FOUND);
        }
        // 修改页面标题
        const APP_NAME = import.meta.env.VITE_APP_NAME;
        const locale = to.meta?.locale;
        if (locale) {
            document.title = locale + '-' + APP_NAME;
        }
        NProgress.done();
    });
}
